package com.xmall.product.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmall.define.dto.product.SkuAttrDto;
import com.xmall.define.dto.product.SkuInfoDto;
import com.xmall.product.define.dto.saleAttr.SpuSaleAttrDto;
import com.xmall.product.define.dto.sku.SkuAttrDo;
import com.xmall.product.define.request.spu.SkuAttrRequest;
import com.xmall.product.entity.SkuAttr;
import com.xmall.product.mapper.SkuAttrMapper;
import com.xmall.product.service.ISkuAttrService;
import com.xmall.product.utils.ConvertUtils;
import com.xmall.utils.ListStreamUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品sku属性 服务实现类
 * </p>
 *
 * @author xmall
 * @since 2023-11-02
 */
@Service
public class SkuAttrServiceImpl extends ServiceImpl<SkuAttrMapper, SkuAttr> implements ISkuAttrService {

    /**
     * 保存
     */
    @Override
    public void save(Long spuId, Long skuId, Map<Long, Long> attrIdMap, List<SkuAttrRequest> skuAttrList) {
        if(CollectionUtil.isNotEmpty(skuAttrList)) {
            skuAttrList.forEach(skuAttr -> {
                skuAttr.setSpuId(spuId);
                skuAttr.setSkuId(skuId);
                skuAttr.setAttrId(attrIdMap.get(skuAttr.getAttrOptionSn()));
            });
            this.saveBatch(ConvertUtils.SkuAttrModule.INSTANCE.toEntityList(skuAttrList));
        }
    }

    /**
     * 填充属性值
     */
    @Override
    public void fillValue(Long spuId, List<SpuSaleAttrDto> saleAttrs) {
        List<SkuAttrDo> list = this.baseMapper.listBySpuId(spuId);
        if (null != list && list.size() > 0) {
            List<Long> optionSnList = list.stream().map(skuAttrDo -> skuAttrDo.getAttrOptionSn()).collect(Collectors.toList());
            saleAttrs.forEach(saleAttr -> saleAttr.getOptionList().forEach(option -> {
                option.setSelected(optionSnList.stream().anyMatch(optionSn -> option.getAttrOptionSn().compareTo(optionSn) == 0));
            }));
        }
    }

    /**
     * 根据sku列表提取sku属性列表（接口使用）
     */
    @Override
    public List<SpuSaleAttrDto> extractSkuAttrList(Map<Long, Integer> wholeAttrSortList, List<SkuInfoDto> skuInfoDtoList) {
        List<SpuSaleAttrDto> result = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(skuInfoDtoList) && skuInfoDtoList.get(0).getSkuAttrList().size() > 0) {
            // 将所有sku属性列表转换成一个集合
            List<SkuAttrDto> skuAttrDtoList = skuInfoDtoList.stream().map(skuInfoDto -> skuInfoDto.getSkuAttrList()).flatMap(Collection::stream).collect(Collectors.toList());

            // attrId -> attrName
            Map<Long, String> attrIdNameMap = skuAttrDtoList.stream().filter(ListStreamUtils.distinctByKey(SkuAttrDto::getAttrId)).collect(Collectors.toMap(SkuAttrDto::getAttrId, SkuAttrDto::getAttrName));

            // attrId -> List<SkuAttrDto>
            Map<Long, List<SkuAttrDto>> skuAttrMap = skuAttrDtoList.stream().collect(Collectors.groupingBy(SkuAttrDto::getAttrId));

            // attrId -> List<SkuAttrDto>，相同attrOptionSn合并
            Map<Long, List<SkuAttrDto>> distinctSkuAttrMap = new HashMap<>();
            skuAttrMap.forEach((attrId, list) -> distinctSkuAttrMap.put(attrId, list.stream().filter(ListStreamUtils.distinctByKey(SkuAttrDto::getAttrOptionSn)).collect(Collectors.toList())));

            // 填充返回类型
            distinctSkuAttrMap.forEach((attrId, list) -> {
                SpuSaleAttrDto attrDto = new SpuSaleAttrDto();
                attrDto.setId(attrId);
                attrDto.setSort(wholeAttrSortList.get(attrId));
                attrDto.setName(attrIdNameMap.get(attrId));
                attrDto.setOptionList(ConvertUtils.SkuAttrModule.INSTANCE.dtoList2valueList(list));
                result.add(attrDto);
            });
            result.sort(Comparator.comparing(SpuSaleAttrDto::getSort));
        }

        return result;
    }

}
